# encoding=utf-8
import nltk

print(nltk.data.path)
# 加载语料库和模型
nltk.download('averaged_perceptron_tagger')
nltk.download('maxent_ne_chunker')
nltk.download('words')

# 定义要抽取信息的文本
text = "Barack Obama was born in Hawaii. He was the 44th President of the United States of America."

# 对文本进行分词和词性标注
tokens = nltk.word_tokenize(text)
tagged = nltk.pos_tag(tokens)

# 使用命名实体识别模型提取实体
entities = nltk.ne_chunk(tagged, binary=True)

# 遍历实体并输出
for subtree in entities.subtrees(filter=lambda t: t.label() == 'NE'):
    entity = ' '.join([word for word, tag in subtree.leaves()])
    print(subtree.label(), "->", entity)
